package com.fetch.fetcher;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import com.fetch.Main;
import com.fetch.bean.Profile;
import com.fetch.common.Configuration;
import com.fetch.common.Constants;
import com.fetch.common.LOG;


public class ListFetcher {
	private String url = "http://218.4.189.213:8001/CorpSel/CorpSearchs.aspx?CrruPage={currPage}&corp_zch=&corp_qymc=&corp_jydz=&corp_frdb=&corp_zczbminvalue=&corp_zczbmaxvalue=&corp_jyfw=&Drp_corp_type=&Drp_copy_hy=&corp_gq=&corp_jyqxminvalue=&corp_jyqxmaxvalue=";
	private HttpClient client = new HttpClient();
	private int category = 0;
	
	public ListFetcher(int category){
		this.category = category;
		if(category == Constants.CATEGORY_PERSON){
			this.url = "http://218.4.189.213:8001/CorpSel/CorpSearchsG.aspx?CrruPage={currPage}&corp_zch=&corp_qymc=&corp_jydz=&corp_frdb=&corp_zczbminvalue=&corp_zczbmaxvalue=&corp_jyfw=&Drp_copy_hy=&corp_gq=&corp_jyqxminvalue=&corp_jyqxmaxvalue=";
		}
	}
	
	public List<Profile> fetch(int currPage){
		PostMethod getMethod = null;
		try{
			getMethod = new PostMethod(url.replace("{currPage}", currPage+""));
			getMethod.addRequestHeader("Cookie", Main.COOKIE);
			client.executeMethod(getMethod);
			String result = getMethod.getResponseBodyAsString();
//			writeFile(currPage, result);
			return parse(result);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			getMethod.releaseConnection();
		}
		return null;
	}
	
	private List<Profile> parse(String source){
		List<Profile> list = new ArrayList<Profile>();
		Pattern pattern = Pattern.compile("<a href=\"Corp_infoG?.aspx\\?corp_id=(\\d+)\">(.*?)</a>&nbsp;&nbsp;(.*)");
		Matcher matcher = pattern.matcher(source);
		while(matcher.find()){
			Profile profile = new Profile();
			profile.setId(matcher.group(1));
			profile.setName(matcher.group(2));
			profile.setDate(matcher.group(3));
			profile.setCategory(category);
			list.add(profile);
		}
		return list;
	}
	
//	private void writeFile(int currPage, String source){
//		FileOutputStream fos = null;
//		try{
//			String path = Configuration.getString("filepath") + "/pages/" + currPage + "/page.html";
//			File file = new File(path);
//			if(!file.getParentFile().exists()){
//				file.getParentFile().mkdirs();
//			}
//			fos = new FileOutputStream(file);
//			fos.write(source.getBytes());
//		}catch (Exception e) {
//			e.printStackTrace();
//		}finally{
//			try {
//				fos.close();
//			} catch (Exception e2) {}
//		}
//	}
	
	public void close(){
		try{
			client.getHttpConnectionManager().closeIdleConnections(0);
		}catch (Exception e) {
		}
	}
	
}
